﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using System.IO;
using System.Web;

namespace IBE
{
    public class Common
    {
        public List<List<T>> Chunk<T>(List<T> theList, int chunkSize)
        {
            List<List<T>> result = theList
                .Select((x, i) => new
                {
                    data = x,
                    indexgroup = i / chunkSize
                })
                .GroupBy(x => x.indexgroup, x => x.data)
                .Select(g => new List<T>(g))
                .ToList();

            return result;
        }

        public DateTime GetDate(string day, string time)
        {
            day = day.Replace("-", "/");
            DateTime date = DateTime.Now;
            CultureInfo provider = CultureInfo.InvariantCulture;
            if (time.Length < 4)
            {
                time = Convert.ToInt32(time).ToString("0000");                
            }
            string format = "yyyyMMdd HHmm";
            if (!DateTime.TryParseExact(day + " " + time, format, provider, DateTimeStyles.None, out date))
            {
                date = DateTime.Now;
            }
            return date;
        }

        public DateTime GetDate(string day, string time, string format)
        {
            DateTime date = DateTime.Now;
            CultureInfo provider = CultureInfo.InvariantCulture;
            if (time.Length < 4)
            {
                time = Convert.ToInt32(time).ToString("0000");
            }
            
            if (!DateTime.TryParseExact(day + " " + time, format, provider, DateTimeStyles.None, out date))
            {
                date = DateTime.Now;
            }
            return date;
        }

        public DateTime GetDateFormat(string day, string format)
        {
            day = day.Replace("-", "/");
            DateTime date = DateTime.Now;
            CultureInfo provider = CultureInfo.InvariantCulture;
            DateTime.TryParseExact(day, format, provider, DateTimeStyles.None, out date);
            return date;
        }

        public static string ConvertEnglishDateTime(DateTime input)
        {
            string month = "";
            switch (input.Month)
            {
                case 1:
                    month = "JAN";
                    break;
                case 2:
                    month = "FEB";
                    break;
                case 3:
                    month = "MAR";
                    break;
                case 4:
                    month = "APR";
                    break;
                case 5:
                    month = "MAY";
                    break;
                case 6:
                    month = "JUN";
                    break;
                case 7:
                    month = "JUL";
                    break;
                case 8:
                    month = "AUG";
                    break;
                case 9:
                    month = "SEP";
                    break;
                case 10:
                    month = "OCT";
                    break;
                case 11:
                    month = "NOV";
                    break;
                case 12:
                    month = "DEC";
                    break;
                default:
                    break;
            }

            return input.Day.ToString("00") + month + input.Year.ToString().Substring(2, 2);
        }

        public string GetRandomForToNumber(int codeCount)
        {
            string allChar = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z";
            string[] allCharArray = allChar.Split(',');
            string randomCode = "";
            int temp = -1;
            Random rand = new Random();
            for (int i = 0; i < codeCount; i++)
            {
                if (temp != -1)
                {
                    rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
                }
                int t = rand.Next(36);
                if (temp != -1 && temp == t)
                {
                    return GetRandomForToNumber(codeCount);
                }
                temp = t;
                randomCode += allCharArray[t];
            }
            return randomCode;
        }

        public static string ConvertToUnSignString(string input)
        {
            const string FindText = "áàảãạâấầẩẫậăắằẳẵặđéèẻẽẹêếềểễệíìỉĩịóòỏõọôốồổỗộơớờởỡợúùủũụưứừửữựýỳỷỹỵÁÀẢÃẠÂẤẦẨẪẬĂẮẰẲẴẶĐÉÈẺẼẸÊẾỀỂỄỆÍÌỈĨỊÓÒỎÕỌÔỐỒỔỖỘƠỚỜỞỠỢÚÙỦŨỤƯỨỪỬỮỰÝỲỶỸỴ";
            const string ReplText = "aaaaaaaaaaaaaaaaadeeeeeeeeeeeiiiiiooooooooooooooooouuuuuuuuuuuyyyyyAAAAAAAAAAAAAAAAADEEEEEEEEEEEIIIIIOOOOOOOOOOOOOOOOOUUUUUUUUUUUYYYYY";
            int index = -1;
            char[] arrChar = FindText.ToCharArray();
            while ((index = input.IndexOfAny(arrChar)) != -1)
            {
                int index2 = FindText.IndexOf(input[index]);
                input = input.Replace(input[index], ReplText[index2]);
            }
            return input.Replace("\'", "");
        }

        public static string SaveFile(string filename, string input)
        {
            string status = "Failed";
            try
            {
                FileInfo file = new FileInfo(filename);
                System.IO.FileStream wFile;
                wFile = new FileStream(filename, FileMode.Append);
                byte[] data = Encoding.UTF8.GetBytes(input);
                wFile.Write(data, 0, data.Length);
                wFile.Close();
                status = "Success";
            }
            catch (IOException ex)
            {
                throw ex;
            }
            return status;
        }

        public static string SaveFile(string filename, string input, bool overwrite)
        {
            string status = "Failed";
            try
            {
                FileInfo file = new FileInfo(filename);
                System.IO.FileStream wFile;
                wFile = new FileStream(filename, FileMode.Create);
                byte[] data = Encoding.UTF8.GetBytes(input);
                wFile.Write(data, 0, data.Length);
                wFile.Close();
                status = "Success";
            }
            catch (IOException ex)
            {
                throw ex;
            }
            return status;
        }

        public static void WriteToFile(string strMsg)
        {
            //Create a Text File
            string systemDrive = AppDomain.CurrentDomain.BaseDirectory;
            string fileLog = systemDrive + @"Log.txt";
            FileStream fs = null;
            if (!System.IO.File.Exists(fileLog))
            {
                using (fs = System.IO.File.Create(fileLog))
                {

                }

                using (StreamWriter sw = System.IO.File.AppendText(fileLog))
                {
                    sw.WriteLine("IBE Log");
                    sw.WriteLine("Version 1.0.0");
                    sw.WriteLine("Copyright 2014 © Nguyen Quang Minh. All rights reserved.");
                    sw.WriteLine("Created by Nguyen Quang Minh");
                    sw.WriteLine("-------------------------------------------------------");
                }
            }

            //Write to a Text File
            if (System.IO.File.Exists(fileLog))
            {
                using (StreamWriter sw = System.IO.File.AppendText(fileLog))
                {
                    sw.WriteLine(DateTime.Now.ToString() + ": " + strMsg);
                }
            }
        }

        public static DateTime GetDateByDayAndTime(string day, string time)
        {
            day = day.Replace("-", "/");
            DateTime date = DateTime.Now;
            CultureInfo provider = CultureInfo.InvariantCulture;
            if (time.Length < 4)
            {
                time = Convert.ToInt32(time).ToString("0000");
            }
            string format = "yyyyMMdd HHmm";
            if (!DateTime.TryParseExact(day + " " + time, format, provider, DateTimeStyles.None, out date))
            {
                date = DateTime.Now;
            }
            return date;
        }

        #region Money exchange
        public static double MoneyExchange(double inputValue, string inputCode, string outputCode)
        {
            return Convert.ToDouble(MoneyExchangeWithContext(HttpContext.Current, Convert.ToDecimal(inputValue), inputCode, outputCode));
        }

        public static decimal MoneyExchange(decimal inputValue, string inputCode, string outputCode)
        {
            return MoneyExchangeWithContext(HttpContext.Current, inputValue, inputCode, outputCode);
        }

        public static decimal MoneyExchangeWithContext(HttpContext context, decimal inputValue, string inputCode, string outputCode)
        {
            NumberFormatInfo provider = new NumberFormatInfo();
            provider.NumberDecimalSeparator = ".";
            provider.NumberGroupSeparator = ",";
            provider.NumberGroupSizes = new int[] { 3 };

            string filepath = "/Config/Currency.ini";
            IniParser parser = new IniParser(context.Server.MapPath(filepath));
            decimal value = 0;
            try
            {
                if (inputCode == outputCode)
                {
                    //Xử lý làm tròn
                    string roundUnit = parser.GetSetting(outputCode, "RoundUnit");
                    if (!String.IsNullOrEmpty(roundUnit))
                    {
                        if (Convert.ToInt32(roundUnit) == -2)
                        {
                            value = Math.Round(inputValue, 2);
                        }
                        else if (Convert.ToInt32(roundUnit) == -1)
                        {
                            value = Math.Round(inputValue, 1);
                        }
                        else if (Convert.ToInt32(roundUnit) == 1)
                        {
                            value = Math.Round(inputValue);
                        }
                        else
                        {
                            value = Math.Round(inputValue / Convert.ToInt32(roundUnit)) * Convert.ToInt32(roundUnit);
                        }
                    }
                    else
                    {
                        value = inputValue;
                    }
                }
                else
                {
                    if (!String.IsNullOrEmpty(parser.GetSetting(outputCode, "Name")))
                    {
                        if (inputCode == "USD")
                        {
                            value = inputValue * Convert.ToDecimal(parser.GetSetting(outputCode, "Rate"), provider);

                        }
                        else
                        {
                            decimal temp = inputValue / Convert.ToDecimal(parser.GetSetting(inputCode, "Rate"), provider);
                            value = temp * Convert.ToDecimal(parser.GetSetting(outputCode, "Rate"), provider);
                        }

                        //Xử lý làm tròn
                        string roundUnit = parser.GetSetting(outputCode, "RoundUnit");
                        if (Convert.ToInt32(roundUnit) == -2)
                        {
                            value = Math.Round(value, 2);
                        }
                        else if (Convert.ToInt32(roundUnit) == -1)
                        {
                            value = Math.Round(value, 1);
                        }
                        else if (Convert.ToInt32(roundUnit) == 1)
                        {
                            value = Math.Round(value);
                        }
                        else
                        {
                            value = Math.Round(value / Convert.ToInt32(roundUnit)) * Convert.ToInt32(roundUnit);
                        }
                    }
                    else
                    {
                        value = inputValue;
                    }
                }
            }
            catch (Exception)
            {
                value = inputValue;
            }

            return value;
        }
        #endregion
    }
}
